#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **split_string(const char *input, int *count) {
    // 去除末尾换行符（如果有）
    char *str = strdup(input);
    if (str == NULL) return NULL;
    str[strcspn(str, "\n")] = '\0';

    // 临时指针遍历字符串
    char *p   = str;
    int   len = strlen(p);

    // 预分配内存（可根据需求调整初始大小）
    int    capacity = 10;
    char **result   = malloc(capacity * sizeof(char *));
    if (result == NULL) {
        free(str);
        return NULL;
    }

    *count = 0;

    while (1) {
        // 跳过空格
        while (*p == ' ') p++;
        if (*p == '\0') break;

        // 记录子字符串起始位置
        char *start = p;

        // 找到下一个空格或结尾
        while (*p != ' ' && *p != '\0') p++;

        // 计算子字符串长度
        int substr_len = p - start;

        // 分配子字符串内存
        char *substr = malloc(substr_len + 1);
        if (substr == NULL) {
            // 内存不足时释放已分配的内存
            for (int i = 0; i < *count; i++) free(result[i]);
            free(result);
            free(str);
            return NULL;
        }

        // 复制子字符串
        strncpy(substr, start, substr_len);
        substr[substr_len] = '\0';

        // 动态扩展数组
        if (*count >= capacity) {
            capacity *= 2;
            char **temp = realloc(result, capacity * sizeof(char *));
            if (temp == NULL) {
                // 处理内存不足
                for (int i = 0; i < *count; i++) free(result[i]);
                free(result);
                free(str);
                return NULL;
            }
            result = temp;
        }

        result[(*count)++] = substr;
    }

    free(str);
    return result;
}

// 示例用法
int main() {
    const char *input = "hello world this is C programming\n";
    int         count;
    char      **arr = split_string(input, &count);

    if (arr != NULL) {
        printf("分割结果（共 %d 项）:\n", count);
        for (int i = 0; i < count; i++) {
            printf("[%d] %s\n", i, arr[i]);
            free(arr[i]); // 释放每个子字符串
        }
        free(arr);        // 释放数组
    }

    return 0;
}